import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.Timer;

/**
 * User: Ryan Green
 * Date: Nov 5, 2010
 * Time: 12:44:49 PM
 * Copyright - University of South Australia
 */
public class mytardis_client {
	String pathsFile = "config/pathConfig.xml"; //the config file

	String trayIconFile = "config/mawson24.gif";

	String logFile = "config/log.txt";
	LogHandler log;

	Config config;

	mytardis_client(String[] args) {

		//for debugging uses - set config file at runtime
		if (args.length == 1) {
			pathsFile = args[1];
		}

		//deal with the log file
		log = new LogHandler(logFile);

		config = new Config(pathsFile, log);

		final TrayIcon trayIcon;

		if (SystemTray.isSupported()) {

			SystemTray tray = SystemTray.getSystemTray();
			Image image = Toolkit.getDefaultToolkit().getImage(trayIconFile);

			ActionListener exitListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					log.LogAndExit("Exiting...");
				}
			};

			ActionListener aboutListener = new ActionListener() {

				public void actionPerformed(ActionEvent actionEvent) {
					new AboutDialog(log);
				}
			};

			ActionListener manualAddListener = new ActionListener() {

				public void actionPerformed(ActionEvent actionEvent) {
					JFileChooser chooser = new JFileChooser();
					if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
						handleFile(chooser.getSelectedFile());
				}
			};

			PopupMenu popup = new PopupMenu();

			MenuItem addItem = new MenuItem("Manually Add Item");
			MenuItem aboutItem = new MenuItem("About");
			MenuItem defaultItem = new MenuItem("Exit");
			defaultItem.addActionListener(exitListener);
			aboutItem.addActionListener(aboutListener);
			addItem.addActionListener(manualAddListener);
			popup.add(addItem);
			popup.add(aboutItem);
			popup.add(defaultItem);

			trayIcon = new TrayIcon(image, "mytardis_client Client", popup);

			ActionListener actionListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					trayIcon.displayMessage("Action Event",
									"An Action Event Has Been Performed!",
									TrayIcon.MessageType.INFO);
				}
			};

			trayIcon.setImageAutoSize(true);
			trayIcon.addActionListener(actionListener);

			try {
				tray.add(trayIcon);
			} catch (Exception e) {
				log.LogAndExit("System tray not supported", true);
			}
		} else {
			log.LogAndExit("System tray not supported", true);
		}

		watch(config.watchFolder, config.watchFilter);
	}

	private void handleFile(File file) {
		try {
			new LoginWindow().setVisible(true);
			new MetaDataWindow().setVisible(true);
			JOptionPane.showMessageDialog(null, "Success");
		} catch (Exception e) {
			log.Log("Error handling new file.", true);
			log.LogAndExit(e.getStackTrace());
		}
	}

	public static void main(String[] args) {
		if (new JustOneLock().isAppActive()) {
			JOptionPane.showMessageDialog(null,
							"Only one instance of mytardis_client is able to be run.\n If you believe this to be in error please\n delete the 'lock.tmp' file in the config directory.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}

		new mytardis_client(args);
	}

	public void watch(String folder, String filter) {
		TimerTask task = new DirWatcher(folder, filter) {
			protected void onChange(File file, String action) {
				//do the action here
				if (action.equals("add")) // a new file has been added
					handleFile(file);
			}
		};

		Timer timer = new Timer();
		timer.schedule(task, new Date(), 1000);

	}

	private void uploadData() {
		//todo this code might prove useful
		/*try {
			URL url = new URL(config.serverAddress);
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode((config.username + ":" + config.password).getBytes()));
			conn.setDoOutput(true);

			ClientHttpRequest req = new ClientHttpRequest(conn);

			req.setParameter("bUploading", "2");
			req.setParameter("DataSource", config.dataSource);
			req.setParameter("FileStream", new File(config.tempFile + ".zip.gpg"));
			req.setParameter("ConfigID", config.configID);

			InputStream response = req.post();

			BufferedInputStream bin = new BufferedInputStream(response);
			int b;
			String returnString = "";
			while ((b = bin.read()) != -1)
				returnString += (char) b;
			response.close();

			if (returnString.indexOf("ERROR") != -1) {

				if (returnString.indexOf("ERROR #822: Access Denied") != -1) {
					do {
						if (askUserPass()) {
							uploadData();
							return;
						} else {
							if (JOptionPane.showConfirmDialog(null, "Are you sure you want to end this session?", "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
								return;
						}
					} while (true);
				} else {
					log.Log("An error occured when uploading to the server.", true);
					log.Log(returnString);
				}
			} else {
				JOptionPane.showMessageDialog(null, "File successfully uploaded to the server.", "Notification", JOptionPane.INFORMATION_MESSAGE);
				log.Log("File successfully uploaded to the server.");
			}

			//add the hash to the hashlist
			hashList.add(currentHash);
			writeHashFile();

			//todo check return string for confirmation msg and display message dialog if all is good
			//todo otherwise display message dialog of any error
			//todo log it either way
		} catch (Exception e) {
			//todo change this to reattempt server communication
			log.Log("An error occurred when communicating with the server.", true);
			log.LogAndExit(e.getStackTrace()) ;
		}*/
	}
}
